package com.zk.servlet; /**
 * @Description
 * @author ZK
 * @time 2021/5/14 20:30
 * @note
 */

import com.zk.domain.Student;
import com.zk.service.StudentService;
import com.zk.service.StudentServiceImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class StudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        int age = Integer.parseInt(request.getParameter("age"));
        Student student = new Student(id, name, email, age);
//        StudentService studentService = new ClassPathXmlApplicationContext("classpath:applicationContext.xml").getBean("studentService", StudentServiceImpl.class);

        WebApplicationContext wac = null;
//        String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
//        Object attribute = request.getServletContext().getAttribute(key);
//        if (attribute != null) {
//            wac = (WebApplicationContext) attribute;
//        }
        // 使用工具类代替上面的
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        StudentService studentService = wac.getBean("studentService", StudentServiceImpl.class);
        studentService.addStudent(student);
        response.sendRedirect(request.getContextPath() + "/index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
